// Global variables
let uploadedData = null;
let processedData = null;
let model = null;
let trainingHistory = {
    accuracy: [],
    val_accuracy: [],
    loss: [],
    val_loss: []
};

// Tab switching function
function switchTab(tabName) {
    // Hide all tab contents
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Remove active class from all tabs
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Show selected tab content
    document.getElementById(`${tabName}-tab`).classList.add('active');
    
    // Set active tab
    document.querySelector(`.tab[onclick="switchTab('${tabName}')"]`).classList.add('active');
}

// Initialize file upload
function initFileUpload() {
    const fileInput = document.getElementById('file-input');
    const dropArea = document.getElementById('drop-area');
    
    fileInput.addEventListener('change', function(e) {
        handleFiles(e.target.files);
    });
    
    dropArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('active');
    });
    
    dropArea.addEventListener('dragleave', function() {
        this.classList.remove('active');
    });
    
    dropArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('active');
        handleFiles(e.dataTransfer.files);
    });
}

// Handle dropped files
function handleFiles(files) {
    if (files.length === 0) return;
    
    const file = files[0];
    if (file.type !== "text/csv" && !file.name.endsWith('.csv')) {
        alert('Please upload a CSV file.');
        return;
    }
    
    // Update file name display
    document.getElementById('file-name').textContent = file.name;
    
    // Parse CSV file
    Papa.parse(file, {
        header: true,
        dynamicTyping: true,
        skipEmptyLines: true,
        complete: function(results) {
            uploadedData = results.data;
            showFileInfo(uploadedData);
        }
    });
}

// Show file information
function showFileInfo(data) {
    // Calculate stats
    const total = data.length;
    const fraud = data.filter(d => d.Class === 1).length;
    const normal = total - fraud;
    const fraudRate = ((fraud / total) * 100).toFixed(3) + '%';
    
    // Update stats
    document.getElementById('uploaded-transactions').textContent = total.toLocaleString();
    document.getElementById('uploaded-fraud').textContent = fraud.toLocaleString();
    document.getElementById('uploaded-normal').textContent = normal.toLocaleString();
    document.getElementById('uploaded-fraud-rate').textContent = fraudRate;
    
    // Show preview table
    const previewTable = document.getElementById('preview-table').getElementsByTagName('tbody')[0];
    previewTable.innerHTML = '';
    
    // Show first 5 rows
    for (let i = 0; i < Math.min(5, data.length); i++) {
        const row = data[i];
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${row.Time}</td>
            <td>${row.V1?.toFixed(6) || ''}</td>
            <td>${row.V2?.toFixed(6) || ''}</td>
            <td>${row.Amount?.toFixed(2) || ''}</td>
            <td>${row.Class === 1 ? 'Fraud' : 'Normal'}</td>
        `;
        previewTable.appendChild(tr);
    }
    
    // Show file info section
    document.getElementById('file-info').style.display = 'block';
}

// Process uploaded data
function processData() {
    if (!uploadedData || uploadedData.length === 0) {
        alert('No data to process!');
        return;
    }
    
    // For demo purposes, simulate processing
    document.getElementById('file-info').style.display = 'none';
    
    // Simulate processing delay
    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';
    progressBar.innerHTML = '<div class="progress" style="width: 0%"></div>';
    
    const processingDiv = document.createElement('div');
    processingDiv.style.textAlign = 'center';
    processingDiv.style.padding = '30px';
    processingDiv.innerHTML = `
        <h3>Processing Data</h3>
        <p>Cleaning, feature engineering, and preparing data for analysis...</p>
    `;
    processingDiv.appendChild(progressBar);
    
    document.getElementById('upload-tab').appendChild(processingDiv);
    
    // Animate progress bar
    let progress = 0;
    const interval = setInterval(() => {
        progress += 5;
        progressBar.querySelector('.progress').style.width = `${progress}%`;
        
        if (progress >= 100) {
            clearInterval(interval);
            processingDiv.innerHTML = `
                <div style="font-size: 48px; color: #4CAF50;">✓</div>
                <h3>Data Processing Complete!</h3>
                <p>${uploadedData.length.toLocaleString()} transactions processed successfully.</p>
                <button class="btn" onclick="switchTab('explore')">Explore Data</button>
            `;
            
            // Enable other tabs
            enableAnalysisTabs();
        }
    }, 150);
}

// Enable analysis tabs after data is processed
function enableAnalysisTabs() {
    // Show content in other tabs
    document.getElementById('explore-content').style.display = 'block';
    document.getElementById('no-data-message').style.display = 'none';
    
    document.getElementById('model-training-content').style.display = 'block';
    document.getElementById('no-data-model').style.display = 'none';
    
    document.getElementById('visual-content').style.display = 'block';
    document.getElementById('no-data-visual').style.display = 'none';
    
    document.getElementById('detect-content').style.display = 'block';
    document.getElementById('no-data-detect').style.display = 'none';
    
    // Update stats in exploration tab
    const total = uploadedData.length;
    const fraud = uploadedData.filter(d => d.Class === 1).length;
    const normal = total - fraud;
    const fraudRate = ((fraud / total) * 100).toFixed(3) + '%';
    
    document.getElementById('total-transactions').textContent = total.toLocaleString();
    document.getElementById('fraud-transactions').textContent = fraud.toLocaleString();
    document.getElementById('normal-transactions').textContent = normal.toLocaleString();
    document.getElementById('fraud-rate').textContent = fraudRate;
    
    // Create charts for data exploration
    createDataCharts();
}

// Create charts for data exploration
function createDataCharts() {
    // Time distribution chart
    const timeCtx = document.getElementById('time-chart').getContext('2d');
    new Chart(timeCtx, {
        type: 'bar',
        data: {
            labels: ['0-20k', '20k-40k', '40k-60k', '60k-80k', '80k-100k', '100k-120k', '120k-140k', '140k-160k', '160k+'],
            datasets: [{
                label: 'Normal Transactions',
                data: [35000, 42000, 38000, 32000,